package com.lccviolet;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @author LiChaochao
 * @Date 2021/9/16 11:53
 * @Description CallableDemo 获得线程的第三种方式
 */
public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<>(new MyThread1());
        new Thread(futureTask, "t1").start();

        // main线程的任务
        int a = 100;

        // futureTask没执行完，就一直等着
        while (!futureTask.isDone()) {

        }

        System.out.println("最终结果：" + (futureTask.get() + a));

    }
}

/*
 * 与实现Runnable接口的区别：
 *       1. 可以指定返回值
 *       2. 抛异常
 *       3. 重写call()方法
 * */
class MyThread1 implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + " come in");
        try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
        return 1024;
    }
}

class MyThread2 implements Runnable {
    @Override
    public void run() {

    }
}

